package com.quotes.datamodell;

import java.util.*;

public class DataTable 
{
	private List<String> columns;
	private List<DataRow> rows;
	
	public DataTable() {
		columns = new ArrayList<String>();
		rows = new ArrayList<DataRow>();
	}
	
	public DataTable(String... columns) {
		this();
		
		for (String column : columns) {
			addColumn(column);
		}
	}
	
	public void addColumn(String column) {
		columns.add(column);
	}
	
	public List<String> getColumns() {
		return columns;
	}
	
	public int getNumberOfColumns() {
		return columns.size();
	}
	
	public void addRow(DataRow row){
		rows.add(row);
	}
	
	public void addRowFromValues(Object... values) {
		DataRow row = new DataRow(values);
		addRow(row);
	}
	
	public DataRow getRow(int index) {
		return rows.get(index);
	}
	
	public List<DataRow> getRows() {
		return rows;
	}
	
	public Object getValue(int rowIndex, int colIndex) {
		return rows.get(rowIndex).getValue(colIndex);
	}
	
	public int getNumberOfRows() {
		return rows.size();
	}
	
	public String toString() {
		String result = "";
		for (DataRow row : rows) {
			result += row.toString() + "\n";
		}
		
		return result;
	}
	
	public void makeFirstRowToHeaders() {
		DataRow row = rows.remove(0);
		for (Object o : row.getCells()) {
			addColumn(o.toString());
		}
	}
	
	public int getColumnIndex(String colName) throws Exception {
		int index = columns.indexOf(colName);
		
		if (index == -1)
			throw new Exception("Column " + colName + " not found in table!");
		
		return index;
	}
	
	public void convertFromExcelDate(String colName) throws Exception {
		int colIndex = getColumnIndex(colName);
		for (DataRow row : rows) {
			row.convertFromExcelDate(colIndex);
		}
	}
	
	public List<Double> getColumnAsDoubles(String colName) throws Exception {
		List<Double> values = new ArrayList<Double>();
		int columnIndex = getColumnIndex(colName);
		
		for (DataRow row : rows) {
			values.add(row.getDoubleValue(columnIndex));
		}
		
		return values;
	}
	
	public List<Date> getColumnAsDates(String colName) throws Exception {
		List<Date> values = new ArrayList<Date>();
		int columnIndex = getColumnIndex(colName);
		
		for (DataRow row : rows) {
			values.add(row.getDateValue(columnIndex));
		}
		
		return values;
	}
	
	public void addColumn(String columnName, Object... data) throws Exception {
		if (data.length != rows.size()) {
			throw new Exception("Count of elements need to be the same like the rows in this table!");
		}
		
		addColumn(columnName);

		for (int i=0; i<data.length; i++) {
			rows.get(i).addCell(data[i]);
		}
	}
}
